<style>
.clipPop {
    width:100%;
    height:100%;
}

.clipImg label.btn {
    width:100%;
    height: 100%;
    display:flex;
    justify-content: center;;
    align-items: center;
    border-radius: 5px;
    border: 1px solid #ccc;
}

.clipImg label.btn > i {
    font-size:30px;
    color:#999;
}

.clipImg label.btn img {
    width:100%;
    height: 100%;
}

.clipImg .el-dialog {
    position: relative;
/*    top:50%;
    left:50%;*/
}

</style>
<template>
<div class="clipImg" :style="{ width: width + 'px', height: height + 'px'}" >
    <label class="btn" for="uploads">
        <i data-v-49e0afea="" class="el-icon-plus" v-if="src == ''"></i>
        <img :src="src" alt="" v-else>
    </label>
    <input type="file" id="uploads" ref="uploads" style="position:absolute; clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
    <el-dialog
        :title="title"
        :visible.sync="state"
        width="790px"
        top="10vh"
        :before-close="handleClose"
        >
        <div class="clipPop" :style="{ width: maxWidth + 'px', height: maxHeight + 'px'}">
            <vueCropper
                ref="cropper"
                :img="img"
                :outputSize="size"
                :outputType="outputType"
                :info="info"
                :canScale="canScale"
                :autoCrop="autoCrop"
                :autoCropWidth="autoCropWidth"
                :autoCropHeight="autoCropHeight"
                :fixed="fixed"
                :fixedNumber="fixedNumber"
                :fixedBox="fixedBox"
            >
            </vueCropper>
        </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="finish('blob')" >确 定</el-button>
      </span>
    </el-dialog>
    <!-- <div class="clip-shadow" v-if="state"></div> -->
</div>

</template>
<script>
  import VueCropper from "vue-cropper"
  import qs from 'qs'

  export default {
    props:{
        img: {
            type:String,
            required:true
        },

        src: {
            type:String
        },

        width: {
            type:String,
            default:320
        },

        height: {
            type:String,
            default:240
        },

        maxWidth: {
            type:String,
            default:750
        },

        maxHeight: {
            type:String,
            default:565
        },

        size: {
            type:Number,
            default:1
        },
        fixedNumber:{
            type:Object,
            default:[1,1]
        },

        fixedBox:{
            type:Boolean,
            default:false
        },

        title:{
            type:String,
            default:'提示'
        },

        info: Boolean,
        fixed: Boolean,
        canScale: Boolean,

    },
    data() {
        return {
            img: '',
            src:"",
            getSrc:'',
            info: true,
            size: 1,
            outputType: 'jpeg',
            canScale: false,
            autoCrop: true,
            // 只有自动截图开启 宽度高度才生效
            autoCropWidth: 340,
            autoCropHeight: 456,
            // 开启宽度和高度比例
            fixed: true,
            fixedNumber: [3, 4],
            state:false,
            title:""
        }
    },

    watch:{
        src(arr){
            // console.log(arr)
        }
    },
    methods:{
        uploadImg (e, num) {
            //上传图片
            // this.option.img
            var file = e.target.files[0]
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                 alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
                 return false
             }
            var reader = new FileReader()
            reader.onload = (e) => {
                let data
                if (typeof e.target.result === 'object') {
                    // 把Array Buffer转化为blob 如果是base64不需要
                    data = window.URL.createObjectURL(new Blob([e.target.result]))
                } else {
                    data = e.target.result
                }

                if (num === 1) {
                    this.img = data
                } else if (num === 2) {
                    this.img = data
                }
            }
            reader.readAsArrayBuffer(file)

            this.state = true
        },


        finish (type) {
            if (type === 'blob') {
                this.$refs.cropper.getCropBlob((data) => {
                    this.getSrc = data
                })
            } else {
                this.$refs.cropper.getCropData((data) => {
                    this.getSrc = data
                })
            }
            this.postFormData()
        },
        //获取签名信息
        getOssConfig() {
            return new Promise((resolve, reject)=>{
                axios.get('/api/system/getOssConfig?platSign=com').then(res=>{
                    res = res.data.data;
                    resolve(res)
                })
            })

        },
        //formData提交
        async postFormData() {
            let data = await this.getOssConfig()
            let idata = await this.aliy(data)

            if(idata.flag == 1) {
                let url = idata.data.params.filename
                this.src = await this.getFull(url)

                this.state =  false
                this.$emit('updateImg', url, this.src)
                // 修复重复图片多次上传不触发
                // document.getElementById('uploads').value = ''
            }
        },

        _guid(){

            function S4 () {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }

            return (S4() + S4() + S4() + S4() + S4() + S4());
        },


        aliy(data) {
            return new Promise((resolve, reject)=>{
                let formData = new FormData();
                    formData.append('policy', data.Policy)
                    formData.append('signature', data.Signature)
                    formData.append('key', data.Dir + this._guid())
                    formData.append('Filename', this._guid());
                    formData.append('OSSAccessKeyId', data.AccessKeyID);
                    formData.append('path', data.Dir)
                    formData.append('callback', data.Callback)
                    formData.append('file', this.getSrc);

                var http = new XMLHttpRequest()

                http.onreadystatechange = function(){
                    if(http.readyState == 4){
                        if(http.status >= 200 && http.status <300 || http.status == 304){
                            resolve(JSON.parse(http.response))
                        }
                    }
                };

                http.open('post', data.Host);
                http.send(formData);
            })
        },

        getFull(key) {
            return new Promise((resolve, reject)=>{
                axios.post('/api/system/getFullUrl', qs.stringify({
                    fileObject:JSON.stringify([{url:key}])
                })).then((res) => {
                    var d = res.data;
                    if(d.flag == 1){
                        resolve(d.data.url)
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            })
        },

        handleClose() {
            this.state = false
            this.$refs.uploads.value = ''
        }
    },

    components:{
        VueCropper
    },

    mounted() {

    }
  }

</script>
